const { page } = require('../../api/index.js')

Page({
  data: {
    recordList: [],
    userInfo: {},
    loading: false,
    reportDialogVisible: false,
    currentReport: null,
    parsedReport: null,
    isViewingOther: false,
    viewingXuehao: null,
    otherName: null
  },
  onLoad(options) {
    // 1. 优先读取页面参数xuehao（用于查看他人档案）
    const xuehaoParam = options && options.xuehao;
    if (xuehaoParam) {
      // 直接用参数学号加载档案
      this.getRecords(xuehaoParam);
      this.setData({ isViewingOther: true, viewingXuehao: xuehaoParam });
      // 优先通过chuangyezhe表获取姓名
      wx.request({
        url: wx.getStorageSync('baseURL') + '/chuangyezhe/query',
        method: 'GET',
        data: { xuehao: xuehaoParam },
        success: (res) => {
          if (res.data && res.data.code === 0 && res.data.data && res.data.data.xueshengxingming) {
            const title = res.data.data.xueshengxingming + '电子档案';
            wx.setNavigationBarTitle({ title });
            this.setData({ otherName: res.data.data.xueshengxingming });
          } else {
            wx.setNavigationBarTitle({ title: '电子档案' });
            this.setData({ otherName: '' });
          }
        },
        fail: (err) => {
          wx.setNavigationBarTitle({ title: '电子档案' });
          this.setData({ otherName: '' });
        }
      });
      return;
    }
    // 2. 否则获取当前用户信息
    wx.request({
      url: wx.getStorageSync('baseURL') + '/chuangyezhe/session',
      method: 'GET',
      header: {
        'Token': wx.getStorageSync('token') || ''
      },
      success: (res) => {
        if (res.data && res.data.data) {
          const userInfo = res.data.data;
          // 校验关键字段
          if (!userInfo.xuehao || !userInfo.xueshengxingming || !userInfo.zhuanye || !userInfo.chuangyelingyu) {
            wx.showToast({ title: '用户信息不完整，请先完善个人信息', icon: 'none' });
            setTimeout(() => {
              wx.navigateTo({ url: '/pages/center/center' });
            }, 1000);
            return;
          }
          this.setData({ userInfo });
          this.getRecords(userInfo.xuehao);
        } else {
          wx.showToast({ title: '获取用户信息失败', icon: 'none' });
          setTimeout(() => {
            wx.navigateTo({ url: '/pages/center/center' });
          }, 1000);
        }
      },
      fail: () => {
        wx.showToast({ title: '获取用户信息失败', icon: 'none' });
        setTimeout(() => {
          wx.navigateTo({ url: '/pages/center/center' });
        }, 1000);
      }
    });
  },
  getRecords(xuehao) {
    const requestUrl = wx.getStorageSync('baseURL') + '/aipersonal/page';
    const requestParams = {
      page: 1,
      limit: 10,
      sort: 'shengchengshijian',
      order: 'desc',
      xuehao: xuehao
    };
    if (!xuehao) return;
    this.setData({ loading: true });
    
    // 使用正确的page函数调用API
    page('aipersonal', requestParams).then(res => {
      if (res && res.code === 0) {
        // 检查数据结构 - request.js已经返回了res.data，所以这里res就是原来的res.data
        const list = res.data?.list || res.list || [];
        
        // 为每个记录生成摘要
        const processedList = list.map(record => {
          return {
            ...record,
            summary: this.generateSummary(record.baogaoneirong),
            rating: this.extractRating(record.baogaoneirong)
          };
        });
        
        // 如果是导师查看他人档案且未获取到otherName，尝试从档案数据中获取姓名
        if (this.data.isViewingOther && !this.data.otherName && processedList.length > 0) {
          const name = processedList[0].xueshengxingming || processedList[0].xingming || '';
          if (name) {
            wx.setNavigationBarTitle({ title: name + '电子档案' });
            this.setData({ otherName: name });
          }
        }
        
        this.setData({ recordList: processedList });
      } else {
        wx.showToast({ title: res?.msg || '获取数据失败', icon: 'none' });
      }
    }).catch(err => {
      wx.showToast({ title: '获取档案列表失败', icon: 'none' });
    }).finally(() => {
      this.setData({ loading: false });
    });
  },
  // 生成报告摘要
  generateSummary(content) {
    if (!content) return '暂无报告内容';
    
    // 移除HTML标签和多余空格
    let plainText = content.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim();
    
    // 清理Markdown标记
    plainText = plainText
      .replace(/#+/g, '') // 去除所有#符号
      .replace(/^[-*]\s*/gm, '') // 去除行首的 - 或 * 符号
      .replace(/^•\s*/gm, '') // 去除行首的 • 符号
      .replace(/\*\*/g, '') // 去除 ** 加粗标记
      .replace(/\*/g, '') // 去除单个 * 符号
      .replace(/\s+/g, ' ') // 合并多个空格
      .trim();
    
    // 提取关键信息
    const summary = [];
    
    // 提取评级
    const rating = this.extractRating(content);
    if (rating) {
      summary.push(`综合评级: ${rating}`);
    }
    
    // 提取前200个字符作为概述
    if (plainText.length > 200) {
      summary.push(plainText.substring(0, 200) + '...');
    } else {
      summary.push(plainText);
    }
    
    return summary.join('\n');
  },
  // 从报告中提取评级（S/A/B/C/D）
  extractRating(content) {
    if (!content) return null;
    const ratingMatch = content.match(/综合评级[：:]\s*([SABCD][\+\-]?)/i);
    if (ratingMatch && ratingMatch[1]) {
      return ratingMatch[1].toUpperCase();
    }
    return null;
  },
  // 获取评级对应的颜色类
  getRatingClass(rating) {
    if (!rating) return 'rating-none';
    if (rating.startsWith('S')) return 'rating-s';
    if (rating.startsWith('A')) return 'rating-a';
    if (rating.startsWith('B')) return 'rating-b';
    if (rating.startsWith('C')) return 'rating-c';
    return 'rating-d';
  },
  async onGenerateAiPersonal() {
    const { userInfo, recordList } = this.data;
    // 检查信息完整性
    if (!userInfo.xuehao || !userInfo.xueshengxingming || !userInfo.zhuanye || !userInfo.chuangyelingyu || !userInfo.canjiahuodong || !userInfo.canyuxiangmu) {
      wx.showToast({ title: '用户信息不完整，请先完善个人信息', icon: 'none' });
      setTimeout(() => {
        wx.navigateTo({ url: '/pages/user-info/user-info' });
      }, 1200);
      return;
    }
    // 预先生成一个进度条列表项
    const now = new Date();
    const tempId = 'generating_' + now.getTime();
    const tempRecord = {
      id: tempId,
      xuehao: userInfo.xuehao,
      xueshengxingming: userInfo.xueshengxingming,
      shengchengshijian: this.formatDate(now),
      generating: true,
      progress: 0
    };
    this.setData({
      recordList: [tempRecord, ...recordList]
    });
    // 进度条动画：6秒到99%
    let progress = 0;
    const updateProgress = () => {
      if (progress < 99) {
        progress += 1;
        this.setData({
          recordList: this.data.recordList.map(r => r.id === tempId ? { ...r, progress } : r)
        });
        setTimeout(updateProgress, 60); // 6秒到99%
      }
    };
    updateProgress();
    wx.showLoading({ title: '生成中，请稍后查看' });
    setTimeout(() => { wx.hideLoading(); }, 2000);
    // 传递完整用户信息
    const { generateAiPersonal } = require('../../api/index.js');
    generateAiPersonal({
      xuehao: userInfo.xuehao,
      xingming: userInfo.xueshengxingming,
      zhuanye: userInfo.zhuanye,
      chuangyelingyu: userInfo.chuangyelingyu,
      canjiahuodong: userInfo.canjiahuodong,
      canyuxiangmu: userInfo.canyuxiangmu
    }).then(res => {
      wx.hideLoading();
      if (res && (res.code === 0 || res.code === 200)) {
        // 进度条到100%，1秒后变回按钮
        this.setData({
          recordList: this.data.recordList.map(r => r.id === tempId ? { ...r, progress: 100 } : r)
        });
        setTimeout(() => {
          this.getRecords(userInfo.xuehao);
        }, 1000);
        wx.showToast({ title: '生成成功', icon: 'success' });
      } else {
        wx.showToast({ title: res?.msg || '生成失败', icon: 'none' });
        // 失败时移除进度条
        this.setData({
          recordList: this.data.recordList.filter(r => r.id !== tempId)
        });
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({ title: '请求失败', icon: 'none' });
      // 失败时移除进度条
      this.setData({
        recordList: this.data.recordList.filter(r => r.id !== tempId)
      });
    });
  },
  viewFullReport(e) {
    const { record } = e.currentTarget.dataset;
    // 直接拼接url
    const url = 'https://chuangyeh.zbvc-quest.com/' + record.baogaoneirong;
    console.log('跳转webview的URL:', url);
    wx.navigateTo({
      url: '/pages/aireport/detail?url=' + encodeURIComponent(url)
    });
  },
  closeReportDialog() {
    this.setData({ reportDialogVisible: false });
  },
  stopPropagation() {
    // 阻止事件冒泡
  },
  formatDate(dateStr) {
    if (!dateStr) return '未知时间';
    
    try {
      // 如果是字符串格式，先处理
      if (typeof dateStr === 'string') {
        // 移除T和Z，并截取到秒
        let formatted = dateStr.replace('T', ' ').replace('Z', '');
        // 如果包含毫秒，去掉毫秒部分
        if (formatted.includes('.')) {
          formatted = formatted.split('.')[0];
        }
        return formatted;
      }
      
      // 如果是Date对象，转换为字符串
      if (dateStr instanceof Date) {
        const year = dateStr.getFullYear();
        const month = String(dateStr.getMonth() + 1).padStart(2, '0');
        const day = String(dateStr.getDate()).padStart(2, '0');
        const hours = String(dateStr.getHours()).padStart(2, '0');
        const minutes = String(dateStr.getMinutes()).padStart(2, '0');
        const seconds = String(dateStr.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
      
      // 如果是数字时间戳
      if (typeof dateStr === 'number') {
        const date = new Date(dateStr);
        return this.formatDate(date);
      }
      
      return '时间格式错误';
    } catch (error) {
      return '时间格式错误';
    }
  },
  // 解析伪Markdown为结构化数据，适配WXML渲染
  parseReportContent(content) {
    if (!content) return [];
    let lines = content.split(/\n+/);
    let result = [];
    let currentList = null;

    lines.forEach((line, index) => {
      line = line.trim();
      if (!line) return;

      // 标题
      let m = line.match(/^(#+)\s*(.*)/);
      if (m) {
        if (currentList) { result.push({ type: 'ul', items: currentList }); currentList = null; }
        // 清理标题文本中的**符号
        let titleText = m[2].replace(/\*\*/g, '').trim();
        const titleItem = { type: 'title', level: m[1].length, text: titleText };
        result.push(titleItem);
        return;
      }
      
      // 处理**标题 - 使用更精确的正则表达式
      let starMatch = line.match(/^\*\*(.+?)\*\*$/);
      if (starMatch) {
        if (currentList) { result.push({ type: 'ul', items: currentList }); currentList = null; }
        const titleItem = { type: 'title', level: 2, text: starMatch[1].trim() };
        result.push(titleItem);
        return;
      }
      
      // 处理以**开头但可能不是严格匹配的行
      if (line.startsWith('**') && line.includes('**')) {
        if (currentList) { result.push({ type: 'ul', items: currentList }); currentList = null; }
        // 使用更可靠的方法提取**之间的内容
        let titleText = line;
        // 移除开头的**
        if (titleText.startsWith('**')) {
          titleText = titleText.substring(2);
        }
        // 移除结尾的**及后面的内容
        let lastStarIndex = titleText.lastIndexOf('**');
        if (lastStarIndex !== -1) {
          titleText = titleText.substring(0, lastStarIndex);
        }
        titleText = titleText.trim();
        
        const titleItem = { type: 'title', level: 2, text: titleText };
        result.push(titleItem);
        return;
      }
      
      // 列表（支持 - 和 * 符号）
      if (/^[-*]/.test(line)) {
        if (!currentList) currentList = [];
        let txt = line.replace(/^[-*]+\s*/, '');
        txt = txt.replace(/^•+\s*/, ''); // 去除行首•
        txt = txt.replace(/^\s+/, ''); // 去除多余空格
        txt = txt.replace(/\*\*/g, ''); // 去除 ** 加粗标记
        txt = txt.replace(/\*/g, ''); // 去除单个 * 符号
        currentList.push(txt);
        return;
      }
      // 普通文本 - 清理掉可能存在的Markdown标记
      if (currentList) { result.push({ type: 'ul', items: currentList }); currentList = null; }
      
      // 清理文本中的Markdown标记
      let cleanText = line
        .replace(/^\s*[-*]\s*/, '') // 去除行首的 - 或 * 符号
        .replace(/^\s*•\s*/, '') // 去除行首的 • 符号
        .replace(/^\s*#+\s*/, '') // 去除行首的 # 符号
        .replace(/\*\*/g, '') // 去除 ** 加粗标记
        .replace(/\*/g, '') // 去除单个 * 符号
        .trim();
      
      let highlight = /评估|建议|风险|综合评级|说明/.test(cleanText);
      const paragraphItem = { type: 'p', text: cleanText, highlight };
      result.push(paragraphItem);
    });
    if (currentList) result.push({ type: 'ul', items: currentList });
    
    return result;
  }
}); 